from typing import Dict, Any, List
from .base_model import BaseLLMModel
from .langgraph_workflows import CommitMessageWorkflow
import logging

logger = logging.getLogger(__name__)

class CommitMessageModelWorkflow(BaseLLMModel):
    """使用LangGraph工作流的Commit Message汇总生成模型 - 保持原有接口"""
    
    def __init__(self, model_name: str = None):
        # 保持与原有CommitMessageModel相同的初始化逻辑
        super().__init__(model_name, temperature=0.1)  # 降低温度以获得更一致的输出
        
        # 初始化LangGraph工作流
        self.workflow = CommitMessageWorkflow(model_name)
    
    def _setup_chain(self):
        """设置commit message汇总生成的LangChain链 - 保持原有接口"""
        # 这里保持原有的链设置，但实际使用工作流
        from langchain_core.prompts import ChatPromptTemplate
        from langchain_core.output_parsers import StrOutputParser
        
        self.commit_prompt_template = ChatPromptTemplate.from_messages([
            ("system", "你是一个专业的Git commit message汇总助手。"),
            ("human", "请生成commit message")
        ])
        self.chain = self.commit_prompt_template | self.llm | StrOutputParser()
    
    def generate_response(self, **kwargs) -> str:
        """实现抽象方法，生成commit message - 保持原有接口"""
        summaries = kwargs.get("summaries", [])
        return self.generate_summary_commit_message(summaries)
    
    def generate_summary_commit_message(self, summaries: List[Dict[str, Any]]) -> str:
        """根据多个summary信息生成一条汇总的commit message - 保持原有接口"""
        try:
            logger.info(f"开始处理 {len(summaries)} 个summary")
            
            # 使用LangGraph工作流，但保持原有的调用方式
            result = self.workflow.generate_summary_commit_message(summaries)
            
            logger.info(f"工作流生成结果: {result}")
            return result
            
        except Exception as e:
            logger.error(f"生成汇总commit message时发生错误: {str(e)}")
            return self._handle_error(e, "生成汇总commit message")
    
    def generate_structured_summary(self, summaries: List[Dict[str, Any]], user_id: str = None, session_id: str = None) -> Dict[str, Any]:
        """生成结构化的汇总commit message - 保持原有接口"""
        logger.info(f"开始生成结构化汇总，输入summaries: {summaries}")
        
        try:
            # 使用LangGraph工作流，但保持原有的调用方式，传递追踪参数
            result = self.workflow.generate_structured_summary(summaries, user_id=user_id, session_id=session_id)
            
            logger.info(f"工作流生成的结构化结果: {result}")
            return result
            
        except Exception as e:
            logger.error(f"生成结构化汇总失败: {str(e)}")
            return {
                "error": f"生成结构化汇总失败: {str(e)}",
                "result": "工作流执行失败"
            }
    
    def _extract_change_types(self, summaries: List[Dict[str, Any]]) -> List[str]:
        """提取变更类型 - 保持原有方法"""
        return self.workflow._extract_change_types(summaries)
    
    def _handle_error(self, error: Exception, operation: str = "操作") -> str:
        """统一错误处理 - 保持原有方法"""
        return f"{operation}时发生错误: {str(error)}"
    
    # 添加工作流特有的方法，用于调试和监控
    def get_workflow_info(self) -> Dict[str, Any]:
        """获取工作流信息"""
        return {
            "workflow_type": "LangGraph",
            "model_name": self.model_name,
            "temperature": self.temperature,
            "workflow_steps": [
                "sort_summaries",
                "extract_contents", 
                "analyze_changes",
                "build_summary_info",
                "generate_commit_message",
                "create_structured_output"
            ]
        }
    
    def run_workflow_with_tracing(self, summaries: List[Dict[str, Any]]) -> Dict[str, Any]:
        """运行工作流并返回详细的执行信息"""
        try:
            result = self.workflow.run(summaries)
            
            return {
                **result,
                "workflow_info": self.get_workflow_info(),
                "execution_trace": True
            }
            
        except Exception as e:
            logger.error(f"工作流执行失败: {str(e)}")
            return {
                "error": f"工作流执行失败: {str(e)}",
                "workflow_info": self.get_workflow_info()
            } 